package com.pet.customer.controller;

import com.pet.customer.mapper.CommentMapper;
import com.pet.customer.mapper.GoodsMapper;
import com.pet.customer.mapper.OrdersMapper;
import com.pet.customer.model.Comment;
import com.pet.customer.model.CommentExample;
import com.pet.customer.model.Goods;
import com.pet.customer.model.Orders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.util.List;


@RestController
public class CommentController {
    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private CommentMapper commentMapper;
    @Autowired
    private GoodsMapper goodsMapper;

    @RequestMapping(value="/comment",method = RequestMethod.POST)
    public String comment(HttpServletRequest request, Model model) throws ParseException {
        String email = (String) request.getSession().getAttribute("email");
        String orderId = request.getParameter("id");
        String content = request.getParameter("content");
        String star = request.getParameter("star");

        Orders orders = ordersMapper.selectByPrimaryKey(Integer.parseInt(orderId));
        int goodsId = orders.getGoodsid();
        int shopId = orders.getShopid();

        Comment comment = new Comment();
        comment.setContent(content);
        comment.setCustomeremail(email);
        comment.setGoodsid(goodsId);
        comment.setOrderid(Integer.parseInt(orderId));
        String starnum = getStar(star);
        comment.setStar(starnum);
        commentMapper.insertSelective(comment);

        orders.setStatus("COMMENTED");
        ordersMapper.updateByPrimaryKeySelective(orders);

        CommentExample commentExample = new CommentExample();
        commentExample.createCriteria().andGoodsidEqualTo(goodsId);
        List<Comment> comments = commentMapper.selectByExample(commentExample);

        int totalStar = 0;
        for(Comment t : comments){
            totalStar += Integer.parseInt(t.getStar());
        }

        int newStar = totalStar/comments.size();

        Goods goods = new Goods();
        goods.setId(goodsId);
        goods.setStar(newStar+"");
        goodsMapper.updateByPrimaryKeySelective(goods);
        return "OK";
    }
    private String getStar(String star){
        if(star.equals("One Star")){
            return "1";
        }
        if(star.equals("Two Stars")){
            return "2";
        }
        if(star.equals("Three Stars")){
            return "3";
        }
        if(star.equals("Four Stars")){
            return "4";
        }
        if(star.equals("Five Stars")){
            return "5";
        }
        return "0";
    }
}